/*
 * Lenovo Group
 * Copyright (c) 2015-2016 All Rights Reserved.
 * Project Name: lmrp-android app
 * Create Time: 16-2-16 下午6:44
 */

package com.lenovo.mso2o.ui.fragment;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationSet;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.ScrollView;

import com.lenovo.framework.base.InjectableFragment;
import com.lenovo.framework.view.ContentLoaderView;
import com.lenovo.mso2o.MSApplication;
import com.lenovo.mso2o.R;
import com.lenovo.mso2o.conf.MSConstants;
import com.lenovo.mso2o.entity.OrderListRequest;
import com.lenovo.mso2o.entity.g.Project;
import com.lenovo.mso2o.entity.g.ProjectDao;
import com.lenovo.mso2o.entity.g.SysDict;
import com.lenovo.mso2o.entity.g.SysDictDao;
import com.lenovo.mso2o.ui.adapter.ConditionSelectAdapter;
import com.lenovo.mso2o.ui.adapter.OrderProjectAdapter;
import com.lenovo.mso2o.ui.adapter.OrderStatusAdapter;
import com.lenovo.mso2o.view.RecycleLayoutManager;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;
import butterknife.OnItemClick;

/**
 * Created by hippo on 12/24/15.
 * filter fragment used for orderfiltering across various lists
 */
public class OrderFilterFragment extends InjectableFragment implements View.OnClickListener, OrderStatusAdapter.OnStautsSelectedListener, OrderProjectAdapter.OnProjectSelectedListener, CompoundButton.OnCheckedChangeListener, ContentLoaderView.OnRefreshListener {
    @Bind(R.id.frame_condition_tab)
    FrameLayout frame_conditiontab;
    @Bind(R.id.order_radio_condition)
    RadioGroup radioGroup_orderlistActiveFragment;
    @Bind(R.id.orderby_condition)
    RadioButton radioButton1;
    @Bind(R.id.filter_condition)
    RadioButton radioButton2;
    @Bind(R.id.orderby_listview_tab)
    ListView list_condition;
    @Bind(R.id.order_status)
    RecyclerView orderStatusRecyclerView;
    @Bind(R.id.order_project)
    RecyclerView orderProjectRecyclerView;
    @Bind(R.id.filter_scrollview_condition)
    ScrollView scroll_condition;
    @Bind(R.id.order_bylist_name)
    LinearLayout linear_name;
    @Bind(R.id.linearProjects)
    LinearLayout linear_main;
    @Bind(R.id.rb_order_grade_high)
    CheckBox highLevel;
    @Bind(R.id.rb_order_grade_middle)
    CheckBox normalLevel;
    @Bind(R.id.rb_order_grade_low)
    CheckBox lowLevel;
    @Bind(R.id.linear_orderStatus)
    LinearLayout linearOrderStatus;

    public OrderListFragment getOrderListFragment() {
        return orderListFragment;
    }

    private OrderListFragment orderListFragment;


    //声明条件参数map

    public final OrderListRequest param = new OrderListRequest();
    private ProjectDao projectDao;//项目库
    private SysDictDao orderStatusDao;//项目状态库
    private List<Project> projectList = null;//项目集合
    private ArrayList<SysDict> states = null;//项目状态集
    private String currentOrderState = "";
    private String currentProject = "";
    private String currentLevel = "";
    private String currentOrderBy = "0";

    private OrderStatusAdapter statusAdapter;//状态适配器
    private OrderProjectAdapter projectAdapter;//项目适配器
    private boolean isOpenMore = false;//打开更多？
    private boolean isStatusMore = false;//状态更多？
    private List<Project> newList = new ArrayList<Project>();//当前显示项目
    private List<SysDict> newDicts = new ArrayList<>();//当前展示状态数目
    private List<String> leftConditions = null;//左侧筛选条件集
    private AnimationSet inAnim;
    private AnimationSet outAnim;
    private int statusLines;
    private int projectLines;
    private int type;//工单类型
    private ConditionSelectAdapter conditionAdapter;

    public static OrderFilterFragment newInstance(Context context, int type) {
        OrderFilterFragment orderFilterFragment = new OrderFilterFragment();
        Bundle b = new Bundle();
        b.putInt(MSConstants.FragmentType.FRAGMENT_ORDERTYPE, type);
        orderFilterFragment.setArguments(b);
        orderFilterFragment.orderListFragment = (OrderListFragment) OrderListFragment.newInstance(context, type);
        orderFilterFragment.initParam(type);
        return orderFilterFragment;
    }

    private void initParam(int type) {
        switch (type) {
            case MSConstants.FragmentType.FRAGMENT_ACTIVORDERS:
                param.setStatus(MSConstants.ListParamConstants.listType_live);
                break;
            case MSConstants.FragmentType.FRAGMENT_GRABORDERS:
                param.setStatus(MSConstants.ListParamConstants.listType_grab);
                break;
            case MSConstants.FragmentType.FRAGMENT_HISTORYORDERS:
                param.setStatus(MSConstants.ListParamConstants.listType_history);
                break;
            case MSConstants.FragmentType.FRAGMENT_RECEIVEORDERS:
                param.setStatus(MSConstants.ListParamConstants.listType_receive);
                break;
        }
    }

    @OnItemClick(R.id.orderby_listview_tab)
    public void onConditionSeleted(AdapterView<?> adapterView, View view, int position, long varl) {
        conditionAdapter.setIndex(position);
        radioButton1.setText(leftConditions.get(position));
        //选中条件请求数据
        param.setSort(null);
        param.setSort(position + "");
        param.setPage(MSConstants.ListParamConstants.page_default);
        orderListFragment.initParams(param, true);
        frame_conditiontab.setVisibility(View.GONE);
    }

    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //two way to instance filterfragment 1. newInstance(context,type) 2. bundle arguments
        Bundle bundle = getArguments();
        if (orderListFragment == null && bundle != null) {
            type = bundle.getInt(MSConstants.FragmentType.FRAGMENT_ORDERTYPE);
            orderListFragment = (OrderListFragment) OrderListFragment.newInstance(getContext(), type);
            initParam(type);
        }
        param.setSort(currentOrderBy);
        param.setPage(MSConstants.ListParamConstants.page_default);
        projectDao = MSApplication.getDaoSession().getProjectDao();
        orderStatusDao = MSApplication.getDaoSession().getSysDictDao();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = super.onCreateView(inflater, container, savedInstanceState);
        if (orderListFragment == null)
            orderListFragment = (OrderListFragment) OrderListFragment.newInstance(getActivity(), type);
        getChildFragmentManager().beginTransaction().replace(R.id.fragment_container, orderListFragment).commit();
        Display currDisplay = getActivity().getWindowManager().getDefaultDisplay();// 获取屏幕当前分辨率
        int displayWidth = currDisplay.getWidth();
        int displayHeight = currDisplay.getHeight() - dip2px(OrderFilterFragment.this.getActivity(), 49)
                - dip2px(OrderFilterFragment.this.getActivity(), 42) - dip2px(OrderFilterFragment.this.getActivity(), 49) - dip2px(OrderFilterFragment.this.getActivity(), 73);
        linear_main.setMinimumHeight(displayHeight);

        leftConditions = new ArrayList<>();
        int size = ConditionSelectAdapter.MAIN_CONDITION.length;
        for (int i = 0; i < size; i++) {
            leftConditions.add(ConditionSelectAdapter.MAIN_CONDITION[i]);
        }

        inAnim = (AnimationSet) AnimationUtils.loadAnimation(getActivity(), R.anim.push_top_in);
        outAnim = (AnimationSet) AnimationUtils.loadAnimation(getActivity(), R.anim.push_top_out);

        conditionAdapter = new ConditionSelectAdapter(leftConditions);
        list_condition.setAdapter(conditionAdapter);

        if (type == MSConstants.FragmentType.FRAGMENT_GRABORDERS)
            linearOrderStatus.setVisibility(View.GONE);
        loadData();

        return view;
    }


    @OnClick(R.id.btn_filter)
    public void onFilterClick(View view) {
        scroll_condition.startAnimation(outAnim);
        frame_conditiontab.setVisibility(View.GONE);
        //删选条件后重新发送请求s
        param.setPage(MSConstants.ListParamConstants.page_default);
        orderListFragment.initParams(param, true);
    }

    @OnClick(R.id.orderby_condition)
    public void onLefClick(View view) {
        if (frame_conditiontab.getVisibility() == View.VISIBLE && list_condition.getVisibility() == View.VISIBLE) {

            list_condition.startAnimation(outAnim);
            frame_conditiontab.setVisibility(View.GONE);

        } else {
            frame_conditiontab.setVisibility(View.VISIBLE);

            list_condition.startAnimation(inAnim);
        }
        scroll_condition.setVisibility(View.GONE);
        list_condition.setVisibility(View.VISIBLE);
    }

    @OnClick(R.id.filter_condition)
    public void onRightClick(View view) {

        if (frame_conditiontab.getVisibility() == View.VISIBLE && scroll_condition.getVisibility() == View.VISIBLE) {

            frame_conditiontab.setVisibility(View.GONE);
            scroll_condition.startAnimation(outAnim);
        } else {
            updateOrderStatusProjects();
            frame_conditiontab.setVisibility(View.VISIBLE);
            scroll_condition.startAnimation(inAnim);
        }
        scroll_condition.setVisibility(View.VISIBLE);
        list_condition.setVisibility(View.GONE);
    }

    private void loadData() {
        radioButton1.setText(leftConditions.get(0));
        //项目展示4个初始化
        statusAdapter = new OrderStatusAdapter(getActivity());
        statusAdapter.setOnMenuSelectedListener(this);
        orderStatusRecyclerView.setAdapter(statusAdapter);
        orderStatusRecyclerView.setHasFixedSize(true);

        projectAdapter = new OrderProjectAdapter(getActivity());
        projectAdapter.setOnMenuSelectedListener(this);
        orderProjectRecyclerView.setAdapter(projectAdapter);
        orderProjectRecyclerView.setHasFixedSize(true);

        updateOrderStatusProjects();
        highLevel.setOnCheckedChangeListener(this);
        normalLevel.setOnCheckedChangeListener(this);
        lowLevel.setOnCheckedChangeListener(this);
        frame_conditiontab.setOnClickListener(this);
        orderListFragment.initParams(param, false);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.frame_condition_tab:
                if (list_condition.getVisibility() == View.VISIBLE)
                    list_condition.startAnimation(outAnim);
                else if (scroll_condition.getVisibility() == View.VISIBLE)
                    scroll_condition.startAnimation(outAnim);
                frame_conditiontab.setVisibility(View.GONE);

                break;

        }

    }

    @Override
    public void onSysDictSelected(SysDict status, int index) {
        if (index == -1) {
            //param.remove(MSConstants.ListParamConstants.billStatus);
        } else {
            currentOrderState = status.getDictCode();
            //param.put(MSConstants.ListParamConstants.billStatus, currentOrderState);
        }
        statusAdapter.notifyDataSetChanged();
    }

    @Override
    public void onProjectSelected(Project project, int index) {
        if (index == -1) {
            //param.remove(MSConstants.ListParamConstants.projectId);
        } else {
            currentProject = project.getProjectId() + "";
            //param.put(MSConstants.ListParamConstants.projectId, currentProject);
        }
        projectAdapter.notifyDataSetChanged();

    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        switch (buttonView.getId()) {
            case R.id.rb_order_grade_high:
                if (isChecked) {
                    currentLevel = MSConstants.ListParamConstants.LEVEL_ORDER[0];
                    normalLevel.setChecked(false);
                    lowLevel.setChecked(false);
                    //param.put(MSConstants.ListParamConstants.billLevel, currentLevel);
                } else {
                    //param.remove(MSConstants.ListParamConstants.billLevel);
                }
                break;
            case R.id.rb_order_grade_middle:
                if (isChecked) {
                    currentLevel = MSConstants.ListParamConstants.LEVEL_ORDER[1];
                    highLevel.setChecked(false);
                    lowLevel.setChecked(false);
                    //param.put(MSConstants.ListParamConstants.billLevel, currentLevel);
                } else {
                    //param.remove(MSConstants.ListParamConstants.billLevel);
                }
                break;
            case R.id.rb_order_grade_low:
                if (isChecked) {
                    currentLevel = MSConstants.ListParamConstants.LEVEL_ORDER[2];
                    normalLevel.setChecked(false);
                    highLevel.setChecked(false);
                    //param.put(MSConstants.ListParamConstants.billLevel, currentLevel);
                } else {
                    //param.remove(MSConstants.ListParamConstants.billLevel);
                }
                break;
        }
    }

    @Override
    public int provideContentRes() {
        return R.layout.order_filter_fragment;
    }

    @Override
    protected void onFragmentInVisible(Bundle savedInstanceState) {
        orderListFragment.onFragmentInVisible(savedInstanceState);
    }

    @Override
    protected void onFragmentVisible(Bundle savedInstanceState) {
        orderListFragment.onFragmentVisible(savedInstanceState);
    }

    @Override
    public void onRefresh(boolean fromSwipe) {
        orderListFragment.onRefresh(fromSwipe);
    }

    public void updateOrderStatusProjects() {
        //项目状态字典库
//        if (states.size() == 0) {
        orderStatusDao = MSApplication.getDaoSession().getSysDictDao();
        states = (ArrayList<SysDict>) orderStatusDao.queryBuilder().where(SysDictDao.Properties.DictType.eq("3")).build().list();
        int slines = states.size() / 4;
        statusLines = states.size() % 4 == 0 ? slines : slines + 1;
        statusAdapter.setListData(states);
        statusAdapter.notifyDataSetChanged();

        orderStatusRecyclerView.setLayoutManager(new RecycleLayoutManager(getActivity(), 4, statusLines));
        statusAdapter.setListData(states);
        statusAdapter.notifyDataSetChanged();
//        }

//        if (projectList.size() == 0) {
        projectDao = MSApplication.getDaoSession().getProjectDao();
        projectList = projectDao.loadAll();
        int plines = projectList.size() / 4;
        projectLines = projectList.size() % 4 == 0 ? plines : plines + 1;
        projectAdapter.setListData(projectList);
        projectAdapter.notifyDataSetChanged();
        if (projectList.size() != 0) {
            linear_name.setVisibility(View.VISIBLE);
        } else {
            linear_name.setVisibility(View.INVISIBLE);
        }

    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    private int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}
